<template>
  <el-dialog
    :width="1600"
    v-model="formVisible"
    :title="props?.title === '' ? '新增抽查' : '新增检查'"
    @close="formCancel"
  >
    <el-form
      ref="ruleFormRef"
      :model="form"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      status-icon
    >
      <el-row :gutter="40" style="width: 100%">
        <el-col :span="12">
          <el-form-item :label="props?.title === '' ? '抽查对象名称' : '检查对象名称'" prop="objectIds">
            <el-select-v2
              v-model="form.objectIds"
              :options="objectNameOptions"
              placeholder="请选择社会组织名称"
              class="select"
              filterable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="抽查时间" prop="spotCheckTime">
            <div style="width: 460px">
              <el-date-picker
                v-model="form.spotCheckTime"
                format="YYYY-MM-DD"
                dateFormat="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="请选择抽查时间"
                style="width: 100%"
                type="datetimerange"
                startPlaceholder="开始时间"
                endPlaceholder="结束时间"
              />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="组织形式" prop="orgFrom">
            <MSelect
              v-model="form.orgFrom"
              placeholder="请选择"
              :options="orgFromOptions"
              class="select"
              multiple
            />
            <el-tooltip
              effect="dark"
              content="书面抽检需上传指定报告"
              placement="top"
            >
              <el-icon size="20" class="box-item"><QuestionFilled /></el-icon>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="props?.title === '' ? '抽检人员' : '检查人员'" prop="operPersonIds">
            <SamplingPersonnel v-model="form.operPersonIds" class="select" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="佐证材料" prop="files">
            <MBackingMaterial
              v-model="form.files"
              dateFormat="YYYY-MM-DD HH:mm"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="props?.title === '' ? '抽查事项' : '检查事项'" prop="itemNames">
            <div style="display: flex; align-items: center; width: 100%">
              <MSelect
                v-model="form.itemNames"
                placeholder="请选择"
                :options="itemNamesOptions"
                class="select"
                style="flex: 1"
                multiple
              />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div style="display: flex; justify-content: flex-end; width: 100%">
        <el-button @click="cancel(ruleFormRef)">取消</el-button>
        <el-button type="primary" @click="submitForm" v-loading="loading">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  <PersonnelSelection ref="PersonnelSelectionRef" />
  <!--抽查事项-->
  <AddSpotChecks ref="addSpotChecksRef" />
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from 'vue'
import { Plu, QuestionFilled } from '@element-plus/icons-vue'
import PersonnelSelection from '../personnelSelection/personnelSelection.vue'
import {
  sorgList,
  getManagerChild,
  addOrUpd,
  soptCheckAdd,
  soptCheckDetail,
  soptCheckUpd
} from '@/api/spotCheck/spotCheck'
import AddSpotChecks from './addSpotChecks/addSpotChecks.vue'
import SamplingPersonnel from '@/views/spotCheck/components/samplingPersonnel/samplingPersonnel.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { dateFormat } from '@/utils'
const objectNameOptions = ref([])
const orgFromOptions = ref([])
const itemNamesOptions = ref([])

const props = defineProps({
  title: {
    type: String,
    default: () => ''
  }
})
const emit = defineEmits(['reload'])
onMounted(() => {
  sorgList().then((res) => {
    objectNameOptions.value = res.data.map((i) => ({
      value: i.sorgInfoId,
      label: i.orgName
    }))
  })
  getManagerChild('OrganizationalForm').then((res) => {
    orgFromOptions.value = res.data.map((i) => ({
      value: Number(i.id),
      label: i.name
    }))
  })
  getManagerChild('spotCheck').then((res) => {
    itemNamesOptions.value = res.data.map((i) => ({
      value: Number(i.id),
      label: i.name
    }))
  })
})

const formVisible = ref(false)

//新增
const form = reactive({
  files: [],
  objectIds: undefined, // 抽查对象名称
  spotCheckTime: undefined, //抽查时间
  orgFrom: [], //组织形式
  orgFromIds: '',
  itemNames: [], //抽查事项
  operPersonIds: [], //抽检人员
  types: 0
})

const rules = ref({
  objectIds: [{ required: true, message: '请选择', trigger: 'change' }],
  spotCheckTime: [{ required: true, message: '请选择', trigger: 'change' }],
  orgFrom: [{ required: true, message: '请选择', trigger: 'change' }],
  itemNames: [{ required: true, message: '请选择', trigger: 'change' }],
  operPersonIds: [{ required: true, message: '请选择', trigger: 'change' }]
})

const save = () => {
  formVisible.value = true
}

const formCancel = () => {
  formVisible.value = false
}

const show = (id, sorgSpotCheckPlanId, type = 0) => {
  formVisible.value = true
  clearForm()
  form.sorgSpotCheckPlanId = sorgSpotCheckPlanId
  form.types = type
  if (id > 0) {
    form.sorgSpotCheckId = id
    //编辑
    soptCheckDetail(id).then((res) => {
      if (Array.isArray(res.data.files) && res.data.files.length > 0) {
        form.files = res.data.files.map((i) => ({
          fileSum: i.filePage,
          isSave: true,
          name: i.fileName,
          createdAt: dateFormat(i.createTime, 'YYYY-MM-DD'),
          time: i.createTime,
          timestamp: i.createTime,
          isAdd: true,
          file: [
            {
              name: i.fileName,
              status: 'success',
              url: i.fileUrl
            }
          ]
        }))
      } else {
        form.files = []
      }

      form.objectIds = res.data.objectIds

      form.spotCheckTime =
        res.data?.spotCheckTime && res.data?.spotCheckEndTime
          ? [res.data.spotCheckTime, res.data.spotCheckEndTime]
          : undefined

      form.orgFrom = res.data?.orgFromIds
        ? res.data.orgFromIds.split(',').map((i) => Number(i))
        : []
      form.itemNames =
        res.data?.itemIds != ''
          ? res.data.itemIds.split(',').map((i) => Number(i))
          : []
      let operPersonNames =
        res.data?.operPersonNames != ''
          ? res.data.operPersonNames.split(',')
          : []
      form.operPersonIds =
        res.data?.operPersonIds != ''
          ? res.data.operPersonIds.split(',').map((i, index) => ({
              value: i,
              name: operPersonNames[index]
            }))
          : []
    })
  }
}

const PersonnelSelectionRef = ref(false)
//抽检人员
const open = () => {
  PersonnelSelectionRef.value.show()
}

//抽检事项
const addSpotChecksRef = ref(false)
const openAddSpotChecks = () => {
  addSpotChecksRef.value.show()
}

// const reload = () => {
//
// }
const loading = ref(false)
const ruleFormRef = ref()
const submitForm = () => {
  console.log('form', form)
  ruleFormRef.value.validate((valid) => {
    if (!valid) return
    let files = form.files
      .filter((i) => i.isSave)
      .map((i) => {
        let file = {
          fileName: i.name,
          filePage: i.fileSum,
          fileUrl: '',
          createTime: i?.isAdd ? i.time : i.timestamp
        }
        if (Array.isArray(i.file) && i.file.length > 0) {
          //上传了文件
          file.fileName = i.name
          file.fileUrl = i.file[0].url
        }
        return file
      })
    let itemNames = form.itemNames
      .map((i) => itemNamesOptions.value.find((j) => j.value === i).label)
      .join(',')
    let orgFrom = form.orgFrom
      .map((i) => orgFromOptions.value.find((j) => j.value === i).label)
      .join(',')
    let orgFromIds = form.orgFrom
      .map((i) => orgFromOptions.value.find((j) => j.value === i).value)
      .join(',')
    let spotCheckTime = form.spotCheckTime[0]
    let spotCheckEndTime = form.spotCheckTime[1]
    let data = {
      ...form,
      files,
      operPersonIds: form.operPersonIds.map((i) => i.value).join(','),
      operPersonNames: form.operPersonIds.map((i) => i.name).join(','),
      itemIds: form.itemNames.join(','),
      itemNames,
      objectName: objectNameOptions.value.find(
        (i) => i.value === form.objectIds
      ).label,
      orgFromIds,
      orgFrom,
      spotCheckTime,
      spotCheckEndTime
    }
    loading.value = true
    let http = form.sorgSpotCheckId ? soptCheckUpd : soptCheckAdd
    http(data)
      .then((res) => {
        ElMessage.success(form.sorgSpotCheckId ? '编辑成功' : '提交成功')
        formVisible.value = false
        emit('reload')
      })
      .finally(() => {
        loading.value = false
      })
  })
}

const clearForm = () => {
  form.files = []
  form.objectIds = undefined
  form.spotCheckTime = undefined
  form.orgFrom = []
  form.orgFromIds = ''
  form.itemNames = []
  form.operPersonIds = []
  form.types = 0
  nextTick(() => {
    ruleFormRef.value.resetFields()
  })
}

// 取消
function cancel() {
  ElMessageBox.confirm('确定进行取消操作？', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      back()
    })
    .catch(() => {})
}

const back = () => {
  clearForm()
  formVisible.value = false
}
defineExpose({ show })
</script>

<style scoped lang="scss">
.search {
  display: flex;
  justify-content: space-between;
}
.btns {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 10px 0;
}
.select {
  width: 480px !important;
}
.box-item {
  margin-left: 20px;
  cursor: pointer;
}
</style>
